import sublime
import sublime_plugin
from datetime import datetime

##
# 功能：逐行替换时间戳为 年月日 （可选中内容执行，或者不选中，全文本执行）
# 例如：
# 指令：view.run_command('example_test')
# 1710842228 => 1710842228 2024-03-19 17:57:08
# 1710842227 => 1710842227 2024-03-19 17:57:07
#
class ExampleTestCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        # 检查是否有选择内容
        selections = self.view.sel()
        if selections and not selections[0].empty():
            self.process_selected(edit, selections)
        else:
            self.process_all(edit)

    def process_selected(self, edit, selections):
        processed_text = ''
        processed_lines = []
        for region in selections:
            print('reigon', region)
            for line1 in self.view.lines(region):
                # 获取选中区域的内容
                selected_content = self.view.substr(line1)
                print(selected_content)
                processed_content = self.process_line(selected_content)
                processed_lines.append(processed_content)
        processed_text = '\n'.join(processed_lines)
        self.view.replace(edit, sublime.Region(selections[0].a, selections[-1].b), processed_text)

    def process_all(self, edit):
        processed_lines = []
        # 获取文本中的所有行
        lines = self.view.lines(sublime.Region(0, self.view.size()))
        for line in lines:
            # 获取当前行的内容
            line_content = self.view.substr(line)
            if not line_content:
                continue
            # 对当前行的内容进行处理
            processed_content = self.process_line(line_content)
            processed_lines.append(processed_content)
        processed_text = '\n'.join(processed_lines)
        self.view.replace(edit, sublime.Region(0, self.view.size()), processed_text)


    def process_line(self, line_content):
        # 这里可以编写对每一行内容的处理逻辑
        line_content = line_content.strip()
        if not line_content.isdigit():
            return ''
        if len(line_content) > 10:
            line_content = line_content[0:10]
        timeArray = time.localtime(int(line_content))
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        newContent = line_content + " " + otherStyleTime
        return line_content + " " + otherStyleTime

        
